package com.xiaoran.commonapi.tencent;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.xiaoran.commonapi.entity.Rst;
import com.xiaoran.commonapi.utils.RedisUtil;
import com.xiaoran.commonapi.utils.SpringUtils;


public class Sms {
    private final RedisUtil redisUtil = new RedisUtil();
    private final Integer limit_seconds;
    private final Integer limit_day;
    private final Integer codeSaveTime;
    private final Rst rst = SpringUtils.getBean(Rst.class);

    public Sms(Integer limit_seconds, Integer limit_day, Integer codeSaveTime) {
        this.limit_day = limit_day;
        this.limit_seconds = limit_seconds;
        this.codeSaveTime = codeSaveTime;
    }

    /**
     * 发送验证码
     *
     * @param phoneNumber 手机号
     * @return rst
     */
    public Rst sendSms(String phoneNumber) {
        String limit_s = phoneNumber + "_limit_seconds";
        String limit_d = phoneNumber + "_limit_day";
        if (!redisUtil.isExpireOrExists(limit_d)) {
            redisUtil.set(phoneNumber + "_limit_day", "0", 24 * 60 * 60);
        }
        if (redisUtil.isExpireOrExists(limit_s)) {
            return rst.error("暂未到达下次发送时间");
        }
        if (Integer.parseInt(redisUtil.get(limit_d)) >= limit_day) {
            return rst.error("24小时内发送短信数已达上限");
        }
        String sendCode = "";
        try {
            Credential cred = new Credential("AKIDPedLnysVt0qQq2yd190atwiDRO5VfYBX", "6vTllU4NPAespWw6zbw1pMcbJkunQmgJ");
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            httpProfile.setConnTimeout(60);
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            SendSmsRequest req = new SendSmsRequest();
            String appid = "1400645215";
            req.setSmsSdkAppId(appid);
            String sign = "时光记录个人网";
            req.setSignName(sign);
            String senderid = "";
            req.setSenderId(senderid);
            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
            String session = "xxx";
            req.setSessionContext(session);
            String extendcode = "";
            req.setExtendCode(extendcode);
            String templateID = "1330276";
            req.setTemplateId(templateID);
            /* 下发手机号码，采用 e.164 标准，+[国家或地区码][手机号]
             * 例如+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
            String[] phoneNumbers_ = new String[1];
            phoneNumbers_[0] = "+86" + phoneNumber;
            // 默认中国
            req.setPhoneNumberSet(phoneNumbers_);
            sendCode = gen4Num();
            String[] templateParams = {"6666", "2"};
            templateParams[0] = sendCode;
            // 验证码是 6666 ，请在2分钟内填写
            req.setTemplateParamSet(templateParams);
//            SendSmsResponse res = client.SendSms(req);
//            SendStatus sendStatusSet = res.getSendStatusSet()[0];
//            if (sendStatusSet.getFee() != 1) {
            if (1 != 1) {
                sendCode = "";
                return rst.error();
            } else {
                // 写入缓存，单个号码限定时间
                redisUtil.set(limit_s, "1", limit_seconds);
                redisUtil.addVal(limit_d, 1);
                // 保存发送的验证码
                redisUtil.set(phoneNumber, sendCode, codeSaveTime);
            }
//            System.out.println(SendSmsResponse.toJsonString(res));
//            System.out.println(res.getRequestId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst.success(sendCode);
    }

    /**
     * 验证验证码
     *
     * @param phone 手机号
     * @param code  验证码
     * @return boolean
     */
    public boolean verifyCode(String phone, String code) {
        return redisUtil.isExpireOrExists(phone) && redisUtil.get(phone).equals(code);
    }

    public static String gen4Num() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
    }
}
